package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器( 登陆之后才能操作)
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        //获取session域对象中的值
        Long empId = (Long) request.getSession().getAttribute("employee");
        Long userId = (Long) request.getSession().getAttribute("user");

        String remoteAddr = request.getRemoteAddr();
        // 员工登录
        if ((empId != null)){
            log.info("请求地址:{} \n 访问路径：{}" ,remoteAddr, request.getRequestURL());
            log.info("员工已登录: id为 " + empId);
            //获取登陆的id
            //将id存入线程空间中
            BaseContext.setCurrentId(empId);
            return true;
        }
        // 用户登录
        if (userId != null){
            log.info("请求地址:{} \n 访问路径：{}" ,remoteAddr, request.getRequestURL());
            log.info("用户已登录: id为 " + userId);
            //获取登陆的id
            //将id存入线程空间中
            BaseContext.setCurrentId(userId);
            return true;
        }
        //用户未登录
        log.info("已拦截请求: \n 请求地址:{} \n 访问路径：{}" ,remoteAddr, request.getRequestURL());
        //没有对象 ,用户没有登陆
        /*throw new LoginException("NOTLOGIN");*/
        log.info("用户未登录");
        R<String> error = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(error));
        return false;
    }

    /**
     * 释放资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
